package com.hd.trans.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.common.interf.VoiceComposeListener;
import com.hd.trans.db.DataBaseMgr;
import com.hd.trans.db.bean.HuDunLanguage;
import com.hd.trans.db.bean.TranslateRecord;
import com.hd.trans.db.bean.VoiceFirstAidKit;
import com.hd.trans.framework.click.XClickUtil;
import com.hd.trans.framework.dialog.SelectVoiceLanguageDialog;
import com.hd.trans.framework.rom.IOUtils;
import com.hd.trans.framework.tools.AppEvents;
import com.hd.trans.framework.tools.HuDunEvent;
import com.hd.trans.framework.tools.ThreadPoolWrapper;
import com.hd.trans.homefun.EventCode;
import com.hd.trans.limit4Use.LimitUseListener;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.ui.base.LimitBaseActivity;
import com.hd.trans.ui.model.SimultaneousModel;
import com.hd.trans.utils.ToastUtils;
import com.hd.trans.utils.TrackerForTrans;
import com.hd.trans.utils.VoicePlayUtil;
import com.hd.trans.widgets.VoicePlayView;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class VoiceFirstAidKitActivity extends LimitBaseActivity {
    @Override
    protected int getLayoutId() {
        return R.layout.activity_voice_first_aid_kit;
    }

    private static final int DELAY_MS = 350;
    private SimultaneousModel mDataModel;
    private VoicePlayUtil voicePlayUtil;
    private HashMap<String, VoiceFirstAidKit> voiceFakHashMap;
    private List<RelativeLayout> rlList;
    private EventCode currentCode = EventCode.VOICE_PLAY_TRANS;
    private String[] scenes;
    private TranslateRecord translateRecord;
    private boolean isVisible;
    private String currentSceneStr;
    private int currentPosition;

    private RelativeLayout rlScene;
    private RelativeLayout rlSceneItem;
    private VoicePlayView voicePlayView;
    private VoicePlayView mCurrentViewVoice;
    private TextView tvOriginal;
    private TextView tvTransContent;
    private TextView fromText;
    private TextView toText;
    private TextView tvScene;
    private View scrollView;
    private View exchange;
    private View leftBt,rightBt;
    private RelativeLayout rlIll;
    private RelativeLayout rlLostPassport;
    private RelativeLayout rlRobbed;
    private RelativeLayout rlGetLost;
    private RelativeLayout rlSmallChange;
    private RelativeLayout rlTrainLeave;
    private RelativeLayout rlPlaneTackOff;

    //open入口
    public static void open(Context context, LimitUseListener listener) {
        setLimitListener(listener);
        Intent intent = new Intent(context, VoiceFirstAidKitActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        super.initViewsAndEvents(savedInstanceState);
        TranslationInterior.getTrackerListener().view(TrackerForTrans.CGJJB);
        //Tts语音播报插件
        voicePlayUtil = VoicePlayUtil.getInstance();

        initView();
        setListener();
        initData();
    }

    @Override
    public void onBackPressed() {
        if(scrollView.getVisibility() == View.GONE){
            rlSceneItem.performClick();
        }else {
            finish();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopPlaying();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        voiceFakHashMap.clear();
        voicePlayUtil.destroy();
    }

    //是否绑定eventbus
    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    /**
     * eventbus 通知语音播放完成。
     *
     * @param event
     */
    @Override
    protected void onXEventRecv(HuDunEvent<?> event) {
        super.onXEventRecv(event);
        switch (event.getEventCode()) {
            case AppEvents.PLAY_COMPLETE: //播放器播放完成
                if (mCurrentViewVoice != null)
                    mCurrentViewVoice.stopPlay();
                break;
        }
    }

    private void initView() {
        rlScene = findViewById(R.id.rl_scene);
        rlSceneItem = findViewById(R.id.rl_scene_item);
        voicePlayView = findViewById(R.id.voice_play_view);
        tvOriginal = findViewById(R.id.tv_original);
        tvTransContent = findViewById(R.id.tv_trans_content);
        tvTransContent.setBackgroundTintList(ColorStateList.valueOf(TranslationInterior.getThemeColor()));
        fromText = findViewById(R.id.tv_from);
        toText = findViewById(R.id.tv_to);
        tvScene = findViewById(R.id.tv_scene);
        scrollView = findViewById(R.id.scroll_view);
        voicePlayView.setOnClickListener(this);
        rlSceneItem.setOnClickListener(this);
        leftBt = findViewById(R.id.left_bt);
        rightBt = findViewById(R.id.right_bt);
        leftBt.setOnClickListener(this);
        rightBt.setOnClickListener(this);
        exchange = findViewById(R.id.icon_exchange);
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.icon_exchange).setOnClickListener(this);

        rlIll = findViewById(R.id.rl_ill);
        rlLostPassport = findViewById(R.id.rl_lost_passport);
        rlRobbed = findViewById(R.id.rl_robbed);
        rlGetLost = findViewById(R.id.rl_get_lost);
        rlSmallChange = findViewById(R.id.rl_small_change);
        rlPlaneTackOff = findViewById(R.id.rl_plane_tack_off);
        rlTrainLeave = findViewById(R.id.rl_train_leave);
        rlIll.setOnClickListener(this);
        rlLostPassport.setOnClickListener(this);
        rlRobbed.setOnClickListener(this);
        rlGetLost.setOnClickListener(this);
        rlSmallChange.setOnClickListener(this);
        rlPlaneTackOff.setOnClickListener(this);
        rlTrainLeave.setOnClickListener(this);
        rlList = new ArrayList<>();
        rlList.add(rlIll);
        rlList.add(rlLostPassport);
        rlList.add(rlRobbed);
        rlList.add(rlGetLost);
        rlList.add(rlSmallChange);
        rlList.add(rlPlaneTackOff);
        rlList.add(rlTrainLeave);


        mDataModel = new ViewModelProvider(this).get(SimultaneousModel.class);
    }

    private void setListener() {
        mDataModel.getLanguageFrom().observe(this, huDunLanguage -> {
            if (huDunLanguage != null) {
                fromText.setText(huDunLanguage.getName());
                changeScene(isVisible, currentSceneStr);
            }
        });
        mDataModel.getLanguageTo().observe(this, huDunLanguage -> {
            if (huDunLanguage != null) {
                toText.setText(huDunLanguage.getName());
                changeScene(isVisible, currentSceneStr);
            }
        });
    }

    private void initData() {
        ThreadPoolWrapper.getInstance().excuseThread(() -> {
            InputStream is = null;
            try {
                is = getAssets().open("voice_first_aid_kit.json");
                String str = IOUtils.toString(is);
                Gson gson = new Gson();
                List<VoiceFirstAidKit> listVoiceFak = gson.fromJson(str, new TypeToken<List<VoiceFirstAidKit>>() {
                }.getType());

                voiceFakHashMap = new HashMap<>();
                for(VoiceFirstAidKit voiceFak:listVoiceFak){
                    voiceFakHashMap.put(voiceFak.getName(), voiceFak);
                }
                listVoiceFak.clear();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(is);
            }
        });

        scenes = getApplication().getResources().getStringArray(R.array.first_aid_kit_scene);

        makeTranslateRecord();

        mDataModel.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName("中文（简体）"));
        mDataModel.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName("英语"));
    }

    private void makeTranslateRecord() {
        translateRecord = new TranslateRecord();
        translateRecord.setTriggerTime(System.currentTimeMillis());
        translateRecord.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName("中文（简体）"));
        translateRecord.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName("英语"));
        translateRecord.setContentTranslate(tvOriginal.getText().toString().trim());
        translateRecord.setContentTranslate(tvTransContent.getText().toString().trim());

    }

    //选择语言弹框
    private void showSelectLanguageDialog(boolean isFromPage) {
        SelectVoiceLanguageDialog.newInstance(mDataModel.getLanguageFrom().getValue(), mDataModel.getLanguageTo().getValue(), isFromPage)
                .setOnLanguageChangedListener((language, isFrom) -> {
                    if (isFrom) {
                        mDataModel.setLanguageFrom(language);
                    } else {
                        mDataModel.setLanguageTo(language);
                    }
                }).show(getSupportFragmentManager(), "VoiceFirstAidKitActivity");
    }

    private void stopPlaying(){
        if(mCurrentViewVoice != null && mCurrentViewVoice.isPlaying()){
            mCurrentViewVoice.stopPlay();
        }
        voicePlayUtil.stopPlay();
    }

    @Override
    public void onClick(View v) {
        if(XClickUtil.isFastDoubleClick(v,XClickUtil.INTERVAL_MILLIS)){
            return;
        }
        int id = v.getId();
        if(id == R.id.back){
            onBackPressed();
        }else if(id == R.id.rl_ill){
            //动画
            outAnimation(0);
        }else if(id == R.id.rl_lost_passport){
            //动画
            outAnimation(1);
        }else if(id == R.id.rl_robbed){
            //动画
            outAnimation(2);
        }else if(id == R.id.rl_get_lost){
            //动画
            outAnimation(3);
        }else if(id == R.id.rl_small_change){
            //动画
            outAnimation(4);
        }else if(id == R.id.rl_plane_tack_off){
            //动画
            outAnimation(5);
        }else if(id == R.id.rl_train_leave){
            //动画
            outAnimation(6);
        }else if(id == R.id.rl_scene_item){
            this.isVisible = false;
            stopPlaying();
            inAnimation();
        }else if(id == R.id.voice_play_view){
            if (!intercept(true)) {
                voicePlayback(voicePlayView);
            }
        }else if(id == R.id.left_bt){
            showSelectLanguageDialog(true);
            stopPlaying();
        }else if(id == R.id.right_bt){
            showSelectLanguageDialog(false);
            stopPlaying();
        }else if(id == R.id.icon_exchange){
            showTranslateAnimation();
            stopPlaying();
        }
    }

    /**
     * 互换语种动画
     */
    private void showTranslateAnimation() {
        if("自动检测".equals(mDataModel.getLanguageFrom().getValue().getName())){
            ToastUtils.showNormal(getResources().getString(R.string.tips_to_not_auto));
            return;
        }
        TranslateAnimation ta1 = new TranslateAnimation(0, leftBt.getWidth() + exchange.getWidth(), 0, 0);
        ta1.setDuration(600);
        ta1.setFillAfter(true);
        leftBt.startAnimation(ta1);
        leftBt.bringToFront();

        TranslateAnimation ta2 = new TranslateAnimation(0, -rightBt.getWidth()-exchange.getWidth(), 0, 0);
        ta2.setDuration(600);
        ta2.setFillAfter(true);
        rightBt.startAnimation(ta2);
        rightBt.bringToFront();

        ta1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                HuDunLanguage fromTemp = mDataModel.getLanguageFrom().getValue();
                mDataModel.setLanguageFrom(mDataModel.getLanguageTo().getValue());
                mDataModel.setLanguageTo(fromTemp);
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        ta2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void outAnimation(int position) {
        TranslationInterior.getTrackerListener().click(
                TrackerForTrans.CGJJB,
                scenes[position],
                TrackerForTrans.UNFOLD
        );

        changeScene(true,scenes[position]);
        currentPosition = position;
        mXHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollView.setVisibility(View.GONE);
            }
        },DELAY_MS);//时长应当略小于动画时长
        for(int i=0;i < rlList.size();i++){
            RelativeLayout view = rlList.get(i);
            Animation animation = null;
            if(i<=position){
                animation = AnimationUtils.loadAnimation(this, R.anim.trans_top_out);//动画时长400毫秒
            }else if(i>position){
                animation = AnimationUtils.loadAnimation(this, R.anim.trans_bottom_out);//动画时长400毫秒
            }
            view.startAnimation(animation);
        }
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.trans_alpha_in);//动画时长500毫秒
        rlScene.startAnimation(animation);
    }

    private void inAnimation(){
        int position = currentPosition;
        for(int i=0;i < rlList.size();i++){
            RelativeLayout view = rlList.get(i);
            Animation animation = null;
            if(i<=position){
                animation = AnimationUtils.loadAnimation(this, R.anim.trans_top_in);
            }else if(i>position){
                animation = AnimationUtils.loadAnimation(this, R.anim.trans_bottom_in);
            }
            view.startAnimation(animation);
        }
        scrollView.setVisibility(View.VISIBLE);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.trans_alpha_out);
        rlScene.startAnimation(animation);
    }

    private void changeScene(boolean isVisible, String sceneStr){
        if(!isVisible)return;
        this.isVisible = true;
        currentSceneStr = sceneStr;
        rlScene.setVisibility(isVisible?View.VISIBLE:View.GONE);
        tvScene.setText(sceneStr);

        String fromLangName = fromText.getText().toString().trim();
        String toLangName = toText.getText().toString().trim();
        VoiceFirstAidKit voiceFakOriginal = voiceFakHashMap.get(fromLangName);
        VoiceFirstAidKit voiceFakTrans = voiceFakHashMap.get(toLangName);
        if (voiceFakOriginal == null) {
            ToastUtils.showNormal("未找到对应"+fromLangName+"的翻译文件");
            return;
        }
        if (voiceFakTrans == null) {
            ToastUtils.showNormal("未找到对应"+toLangName+"的翻译文件");
            return;
        }
        String originalContent = null;
        String transContent = null;
        long triggerTime = 0L;
        if(sceneStr.equals(getResources().getString(R.string.scene_ill_str))){
            originalContent = voiceFakOriginal.getSceneIll();
            transContent = voiceFakTrans.getSceneIll();
            triggerTime = voiceFakTrans.getSceneIllId();
        }else if(sceneStr.equals(getResources().getString(R.string.scene_lost_passport_str))){
            originalContent = voiceFakOriginal.getSceneLostPassport();
            transContent = voiceFakTrans.getSceneLostPassport();
            triggerTime = voiceFakTrans.getSceneLostPassportId();
        }else if(sceneStr.equals(getResources().getString(R.string.scene_robbed_str))){
            originalContent = voiceFakOriginal.getSceneRobbed();
            transContent = voiceFakTrans.getSceneRobbed();
            triggerTime = voiceFakTrans.getSceneRobbedId();
        }else if(sceneStr.equals(getResources().getString(R.string.scene_get_lost_str))){
            originalContent = voiceFakOriginal.getSceneGetLost();
            transContent = voiceFakTrans.getSceneGetLost();
            triggerTime = voiceFakTrans.getSceneGetLostId();
        }else if(sceneStr.equals(getResources().getString(R.string.scene_small_str))){
            originalContent = voiceFakOriginal.getSceneSmallChange();
            transContent = voiceFakTrans.getSceneSmallChange();
            triggerTime = voiceFakTrans.getSceneSmallChangeId();
        }else if(sceneStr.equals(getResources().getString(R.string.scene_plane_tack_str))){
            originalContent = voiceFakOriginal.getScenePlaneTackOff();
            transContent = voiceFakTrans.getScenePlaneTackOff();
            triggerTime = voiceFakTrans.getScenePlaneTackOffId();
        }else if(sceneStr.equals(getResources().getString(R.string.scene_train_leave_str))){
            originalContent = voiceFakOriginal.getSceneTrainLeave();
            transContent = voiceFakTrans.getSceneTrainLeave();
            triggerTime = voiceFakTrans.getSceneTrainLeaveId();
        }
        tvOriginal.setText(originalContent);
        tvTransContent.setText(transContent);

        translateRecord.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName(fromLangName));
        translateRecord.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName(toLangName));
        translateRecord.setTriggerTime(triggerTime);
        translateRecord.setContentOrig(originalContent);
        translateRecord.setContentTranslate(transContent);

        if(PreferenceMgr.getInstance().getTranslatePreference().getVoiceAuto()){

            mXHandler.removeCallbacks(playRunnable);
            mXHandler.postDelayed(playRunnable,DELAY_MS+100);
        }
    }

    private Runnable playRunnable = new Runnable() {
        @Override
        public void run() {
            if (!intercept(true)) {
                voicePlayView.performClick();
            }
        }
    };

    /**
     * 语音播报
     */
    private void voicePlayback(VoicePlayView mVoicePlayView){
        /*mCurrentViewVoice = voicePlayUtil
                .executeTtsPlay(voicePlayView,mCurrentViewVoice,translateRecord,true);*/

        if(voicePlayUtil.isPlaying()){
            voicePlayUtil.stopPlay();
        }
        if(mCurrentViewVoice != null){
            mCurrentViewVoice.loadingComplete();
            if(mCurrentViewVoice.isPlaying()){
                mCurrentViewVoice.stopPlay();
                if(mCurrentViewVoice == mVoicePlayView)
                    return;
            }
        }

        mCurrentViewVoice = mVoicePlayView;

        if(translateRecord == null
                || translateRecord.getLanguageFrom() == null
                || translateRecord.getLanguageTo() == null
                || TextUtils.isEmpty(translateRecord.getContentTranslate())
                || TextUtils.isEmpty(translateRecord.getContentOrig())){
            return;
        }

        String ttsCode = translateRecord.getIsReverse() ? translateRecord.getLanguageFrom().getTtsCode() : translateRecord.getLanguageTo().getTtsCode();
        voicePlayUtil.executeCompositeFile(ttsCode, translateRecord.getContentTranslate(), new VoiceComposeListener() {
            @Override
            public void onStarting() {

                mCurrentViewVoice.loading();
            }

            @Override
            public void onCompleted(String file, boolean isLocal) {
                if(scrollView.getVisibility() == View.GONE){
                    mCurrentViewVoice.startPlay();
                    voicePlayUtil.startPlay(file);
                    if(!isLocal){
                        consumeFreeTrial();
                    }
                }
            }

            @Override
            public void onDownloadFailed() {
                mCurrentViewVoice.loadingFailed();
                voicePlayUtil.stopPlay();
            }
        });
    }

    @NonNull
    @Override
    public EventCode getPageType() {
        return EventCode.VOICE_FIRST_AID_KIT;
    }
}
